//
//  STLaunchScreenViewController.swift
//  iPhone
//
//  Created by Toj on 4/7/23.
//

import UIKit

protocol STFullScreenAdControllerDelegate: NSObjectProtocol {
    
    func fullScreenAdControllerDidPresent(_ viewContrller: STFullScreenAdController)
    
    func fullScreenAdControllerWillDismiss(_ viewContrller: STFullScreenAdController)
    func fullScreenAdControllerDidDismiss(_ viewContrller: STFullScreenAdController)
    
    func fullScreenAdControllerDidTapAd(_ viewContrller: STFullScreenAdController)
}

// MARK: - 懒加载(属性), 变量, 初始化init
class STFullScreenAdController: STBaseViewController {
    var fromViewController: UIViewController?
    
    var admobModel: STAdmobModel?
    weak var ls_delegate: STFullScreenAdControllerDelegate?
    
    open override var shouldAutorotate: Bool {
        return true
    }
    
    // 支持哪些屏幕方向
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    private(set) lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = 0xBDBDBD.to_color
        view.contentMode = .scaleAspectFill
        return view
    }()
    
    private lazy var skipButton: UIButton = {
        let view = UIButton(type: UIButton.ButtonType.custom)
        view.backgroundColor = UIColor(white: 0, alpha: 0.4)
        view.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
        view.cm_cornerRadius = 16
        view.addTarget(self, action: #selector(didTapSkip), for: .touchUpInside)
        return view
    }()
    
    private lazy var closeButton: UIButton = {
        let view = UIButton(type: UIButton.ButtonType.custom)
        view.backgroundColor = UIColor(white: 0, alpha: 0.4)
        view.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
        view.cm_cornerRadius = 16
        view.addTarget(self, action: #selector(didTapClose), for: .touchUpInside)
        return view
    }()
    
    private var startTime: CFAbsoluteTime = 0
    
    private var skipCountdown = 0
    private weak var timer: Timer?
    
    deinit {
        print("-->toj: \(cm_className) func: deinit")
    }
}

// MARK: - 生命周期
extension STFullScreenAdController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ls_delegate?.fullScreenAdControllerDidPresent(self)
        
        setupMakeInitialize()
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
}

// MARK: - 点击事件
private extension STFullScreenAdController {
    
    // 跳过广告的点击事件
    @objc func didTapSkip() {
        
        //报数
        // let endTime = CFAbsoluteTimeGetCurrent()
        // let appearTime = endTime - startTime
        stopTimer()
        launchScreenDismiss()
        
        //        let initSkipTime = STCountDownTimer.shared.endTimeFromLaunched()
        //        let event = DSEvent.init(category:"iOS_launch_ad", action:"adshow_success", label:"skip", lt:.ss)
        //        let msg = [
        //            "deal_time"   : "\(appearTime)",
        //            "init_time"   : "\(initSkipTime)"
        //        ]
        //        DataStatistics.sendEvent(event: event, msg: msg)
    }
    
    @objc func didTapClose() {
        let presented = fromViewController as? STOrientationController
        presented?.isShowAd = false
//        presented?.reloadSupportedRotation()
        dismiss(animated: true)
    }
    
    @objc func countdownCallBack() {
        let skip = "跳过"
        //let skip = OLLocalize("ads_button_skip")
        var title = skip
        skipCountdown -= 1
        if skipCountdown > 0 {
            title = "\(skipCountdown)s " + skip
            skipButton.setTitle(title, for: .normal)
            return
        }
        
        skipButton.setTitle(title, for: .normal)
        stopTimer()
        launchScreenDismiss()
        
        //            let adEndTime = STCountDownTimer.shared.endTime(target: "ad")
        //            let initialTime = STCountDownTimer.shared.endTimeFromLaunched()
        //
        //            let adevent = DSEvent.init(category: "iOS_launch_ad", action: "adshow_success", label: "noskip", lt: .ss)
        //            let admsg = [
        //                "deal_time"   : "\(adEndTime)",
        //                "init_time"   : "\(initialTime)"
        //            ]
        //            DataStatistics.sendEvent(event: adevent, msg: admsg)
        
    }
    
    @objc func didTapImage() {
        guard let _ = admobModel else { return }
        ls_delegate?.fullScreenAdControllerDidTapAd(self)
//        let notiInfo = ["ios_target":target,"launch_ad":"true"]
//        let needLogin = PushMessageModule.needLogin(with: notiInfo)
//        if STUserModel.shared.activate && (STUserModel.shared.loginState || !needLogin) { //已登录直接跳转 或者 不需要登录的
//            PushMessageModule.pushTargetViewController(notiInfo: notiInfo)
//        }else{ //已登录成功后会取值跳转
//            STUserModel.shared.notiInfo = notiInfo
//        }
        skipCountdown = 0
        countdownCallBack()
    }
}

// MARK: - Private
private extension STFullScreenAdController {
    
    func startTimer() {
        if timer != nil {
            stopTimer()
        }
        
        let atimer = Timer.st_scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countdownCallBack))
        timer = atimer
    }
    
    func stopTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func launchScreenDismiss() {
        ls_delegate?.fullScreenAdControllerWillDismiss(self)
        ls_delegate?.fullScreenAdControllerDidDismiss(self)
    }
}

// MARK: - 初始化设置
private extension STFullScreenAdController {
    
    func setupMakeAddSubviews() {
        view.addSubview(imageView)
        view.addSubview(skipButton)
        view.addSubview(closeButton)
    }
    
    func setupMakeLayoutSubviews() {
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        skipButton.snp.makeConstraints { (make) in
            make.top.equalTo(view).inset(CGFloat.sts_barHeight-4)
            make.right.equalTo(view).inset(10.ui_scale)
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(32)
        }
        
        closeButton.snp.makeConstraints { (make) in
            make.top.equalTo(view).inset(CGFloat.nav_barFullHeight*0.5)
            make.left.equalTo(view).inset(10.ui_scale)
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(32)
        }
    }
    
    func setupMakeInitialize() {
        view.backgroundColor = 0xBDBDBD.to_color
        
        closeButton.setTitle("关闭", for: .normal)
        
        startTime = CFAbsoluteTimeGetCurrent()
        skipCountdown = admobModel?.show_time ?? 0
        countdownCallBack()
        startTimer()
        
        imageView.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: #selector(didTapImage))
        imageView.addGestureRecognizer(gesture)
    }
}
